package com.esperia09.webservice.mixibot.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;

public class SendRequest {
	private static final int CONNECTION_TIMEOUT = 20000;

	/**
	 * postメソッドでデータを送る
	 * @param postString
	 * @return
	 * @throws IOException
	 */
	public static String sendPost(HttpURLConnection con, String postString) throws IOException {

	    con.setRequestMethod("POST");
	    con.setDoOutput(true);
	    con.setConnectTimeout(CONNECTION_TIMEOUT);
	    
	    String result = readResponse(con, postString);
		
		return result;
	}
	/**
	 * get
	 * @param getString
	 * @return
	 * @throws IOException
	 */
	public static String sendGet(HttpURLConnection con) throws IOException {

	    con.setRequestMethod("GET");
	    con.setDoOutput(true);
	    con.setConnectTimeout(CONNECTION_TIMEOUT);
	    
	    String result = readResponse(con, "");
		
		return result;
	}
	
	/**
	 * connectionした結果を読み取る
	 * @param con
	 * @param postString
	 * @return
	 * @throws IOException
	 */
	private static String readResponse(HttpURLConnection con, String postString) throws IOException {
		String result = "";
		BufferedReader in = null;
		PrintWriter writer = null;
		
		try {
		    writer = new PrintWriter(con.getOutputStream());
		    writer.print(postString);
		    writer.close();

		    in = new BufferedReader(new InputStreamReader(con.getInputStream()));

		    String line;
		    while ((line = in.readLine()) != null) {
		        result += line;
		    }
		} catch (Exception e) {
		    e.printStackTrace();
		} finally {
		    if (writer != null) writer.close();
		    if (in != null) in.close();
		    if (con != null) con.disconnect();
		}
		
		return result;
	}
}
